package controller

import (
	"encoding/base64"
	"errors"
	"go-gateway-learn/dao"
	"go-gateway-learn/dto"
	"go-gateway-learn/golang_common/lib"
	"go-gateway-learn/middleware"
	"go-gateway-learn/public"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)


type OAuthController struct {
}

func OAuthRegister(routerGroup *gin.RouterGroup) {
	oauth := &OAuthController{}
	routerGroup.POST("/tokens", oauth.Tokens)
	
}

// Tokens godoc
// @Summary 获取TOKENS
// @Description 获取TOKENS
// @Tags OAUTH
// @ID /oauth/okens
// @Accept  json
// @Produce  json
// @Param Adminbody body dto.TokensInput true "body"
// @Success 200 {object} middleware.Response{data=dto.TokensOutput} "success"
// @Router /oauth/tokens [post]
func (oauth *OAuthController) Tokens(c *gin.Context) {
	param := &dto.TokensInput{}
	if err := param.BindValid(c); err != nil {
		middleware.ResponseError(c, 2000, err)
		return
	}
	splits :=strings.Split(c.GetHeader("Authorization")," ")
	if len(splits) != 2{
		middleware.ResponseError(c,2001,errors.New("用户名或密码格式错误！"))
		return
	}

	secret, err :=base64.StdEncoding.DecodeString(splits[1])
	if err != nil{
		middleware.ResponseError(c,2002,err)
		return
	}
	partsSecret := strings.Split(string(secret),":")
	if len(partsSecret) != 2{
		middleware.ResponseError(c,2003,errors.New("用户名或密码格式错误！"))
		return
	}
	appList := dao.AppManagerHandler.GetAppList()
	for _,appInfo :=range appList{
		if appInfo.AppID==partsSecret[0] && appInfo.Secret==partsSecret[1]{
			claims := jwt.StandardClaims{
				Issuer: appInfo.AppID,
				ExpiresAt: time.Now().Add(public.JwtExpires*time.Second).In(lib.TimeLocation).Unix(),
			}
			token, err :=public.JwtEncode(claims)
			if err != nil{
				middleware.ResponseError(c,2004,err)
				return
			}
			out := &dto.TokensOutput{
				ExpiresIn: public.JwtExpires,
				TokenType: "Bearer",
				AccessToken: token,
				Scope: "read_write",
			}
			middleware.ResponseSuccess(c, out)
			return
		}
	}
	middleware.ResponseError(c,2005,errors.New("未能匹配到APP！"))
}